package server

import (
	"context"
	"fmt"
	"github.com/spf13/cast"
	"net/http"
)

type HTTPService interface {
	Open() error
	Close(ctx context.Context) error
	RegisterHandle(path string, handle func(http.ResponseWriter, *http.Request)) error
}

// CreatHttpService 创建一个HTTPService
func CreatHttpService(port int) HTTPService {
	server := &httpServer{port, &http.Server{Addr: ":" + cast.ToString(port)}, http.NewServeMux()}
	server.Server.Handler = server.Routerlist
	return server
}

type httpServer struct {
	Port       int
	Server     *http.Server
	Routerlist *http.ServeMux
}

// Open 执行该方法会被阻塞，应使用goruntion来开启
func (h *httpServer) Open() error {
	err := fmt.Errorf("%d服务：%w", h.Port, h.Server.ListenAndServe())
	// 监听服务出现失败，可能的原因就是它，主动close的肯定不算
	return err
}

func (h *httpServer) Close(ctx context.Context) error {
	err := h.Server.Shutdown(ctx)
	return err
}

func (h *httpServer) RegisterHandle(path string, handle func(http.ResponseWriter, *http.Request)) error {
	h.Routerlist.HandleFunc(path, handle)
	return nil
}
